package com.yzd.netmonitor.service.base;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yzd.netmonitor.dao.base.MyBatisBaseDao;
import com.yzd.netmonitor.page.PageDataBean;

public abstract class AbstractMyBatisBaseService<T extends Serializable, PK extends Serializable, DAO extends MyBatisBaseDao<T, PK>> implements MyBatisBaseService<T, PK, DAO> {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	protected abstract DAO getDao();

	@Override
	public void save(T entity) {

		this.getDao().save(entity);
	}

	@Override
	public void update(T entity) {

		this.getDao().update(entity);
	}

	@Override
	public void saveOrUpdate(T entity) {

		this.getDao().saveOrUpdate(entity);
	}

	@Override
	public void saveOrUpdateBatch(List<T> list) {

		this.getDao().saveOrUpdateBatch(list);
	}

	@Override
	public T get(PK id) {

		return this.getDao().get(id);
	}
	
	@Override
	public List<T> getAll(PK id) {

		return this.getDao().getAll(id);
	}

	@Override
	public void batchExecute(List<T> list, int batchSize) {

		int i = 0;
		List<T> temp = new ArrayList<>();
		for (T o : list) {
			temp.add(o);
			i++;
			if (i == batchSize) {
				this.getDao().saveOrUpdateBatch(temp);
				temp.clear();
				i = 0;
			}
		}
		if (CollectionUtils.isNotEmpty(temp)) {
			this.getDao().saveOrUpdateBatch(temp);
			temp.clear();
		}
	}

	@Override
	public List<T> find(Map<String, Object> params) {

		return this.getDao().find(params);
	}

	@Override
	public PageDataBean<T> findPageDataBean(Map<String, Object> params, int pageNum, int pageSize, String orderField, String orderType) {

		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.putAll(params);
		parameters.put("orderField", orderField);
		parameters.put("orderType", orderType);
		parameters.put("start", (pageNum - 1) * pageSize);
		parameters.put("size", pageSize);
		PageDataBean<T> pageData = null;
		int count = this.getDao().count(parameters);
		List<T> list = this.getDao().find(parameters);
		if (count > 0 && list != null && list.size() > 0) {
			pageData = new PageDataBean<T>();
			pageData.setCount(count);
			pageData.setData(list);
		}
		return pageData;
	}

	@Override
	public void deleteById(PK[] ids) {

		for (PK id : ids) {
			this.getDao().deleteById(id);
		}
	}
}
